package com.ruoyi.web.controller.app.service;

import com.alibaba.fastjson.JSON;
import com.ruoyi.sj.domain.Order;
import com.ruoyi.sj.domain.PayRank;
import com.ruoyi.sj.mapper.OrderMapper;
import com.ruoyi.sj.mapper.PayRankMapper;
import com.ruoyi.util.SerialNumber;
import com.ruoyi.web.controller.app.request.RequestRechargeEntity;
import com.ruoyi.web.controller.pay.PayComponent;
import com.ruoyi.web.controller.pay.PayResponseBody;
import com.ruoyi.web.controller.pay.PayResponseData;
import com.ruoyi.web.controller.pay.ToPayEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @ClassName AppQianYiFuService
 * @Description TODO
 * @Author tyc@yanyu
 * @Date 2018/12/24 0024 11:36
 **/
@Slf4j
@Service
public class AppQianYiFuService {

    @Autowired
    private PayComponent payComponent;

    @Autowired
    private PayRankMapper payRankMapper;

    private SerialNumber serial = new SerialNumber("CZ");

    /**
     * 乾易付下单
     */
    public Object createOrder(ToPayEntity entity) {
        return payComponent.sendToPay(entity);
    }

    /**
     * 支付回调
     */
    public Object getPayBack(PayResponseBody entity) {
        PayResponseData responseData = JSON.parseObject(entity.getResponseParameters(), PayResponseData.class);
        log.info("getPayBack = {} ", entity);
        log.info("responseData = {} ", responseData);
        if (payComponent.verifyMessageByP1(entity)) {
            log.info("getPayBack...验签成功 ");
            payComponent.hanldeSuccess(responseData.getMerMerOrderNo());
        }
        return null;
    }

    /**
     * 充值
     */
    public Object recharge(RequestRechargeEntity entity) {
        // 生成充值
        PayRank payRank = new PayRank();
        payRank.setCreateBy(entity.getMemberId().toString());
        payRank.setCreateDate(new Date());
        payRank.setStatus(0);
        payRank.setPayMoney(new BigDecimal(entity.getMoney()));
        payRankMapper.insertPayRank(payRank);

        //生成订单
        Order order = new Order();
        order.setSn(serial.getAtomicNumber());//生成订单号
        order.setType(1);
        order.setRemark(entity.getRemarks());
        order.setMemberId(entity.getMemberId().toString());
        order.setCreateDate(new Date());
        order.setTitle("充值");
        order.setPayMoney(entity.getMoney());
        order.setPayType(entity.getPayType());
        order.setGoodsId(payRank.getId().toString());
        payComponent.sendToPay(order);
        return order;
    }
}